package com.zengqingfa.odd;

import java.util.concurrent.Semaphore;

/**
 * @fileName: PrintOddEven3
 * @author: zengqingfa
 * @date: 2022/12/14 17:39
 * @description:
 */
public class PrintOddEven3 {

    public static int count;

    private static Semaphore semaphore1 = new Semaphore(1);

    private static Semaphore semaphore2 = new Semaphore(0);


    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    try {
                        semaphore1.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (count % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + "：" + count++);
                    }
                    semaphore2.release();
                }
            }
        }, "偶数线程").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100) {
                    try {
                        semaphore2.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (count % 2 == 1) {
                        System.out.println(Thread.currentThread().getName() + "：" + count++);
                    }
                    semaphore1.release();
                }
            }
        }, "奇数线程").start();
    }
}
